package com.zm.zmgz.interceptorzm;

import com.zm.zmgz.pojo.UserBean;
import com.zm.zmgz.pojo.UserNameAndIpBean;
import com.zm.zmgz.utils.HttpServletRequestCjwUtils;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Objects;

/**
 * Created with IntelliJ IDEA.
 *
 * @Auther: cjw
 * @Date: 2020/04/06/14:19
 * @Description: 将当前线程名设置为用户名加用户ip
 */
public class SetThreadNameByUserNameInterceptor extends HandlerInterceptorAdapter {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 获取token(身份证)
        ServletContext servletContext = request.getServletContext();
        String token = request.getHeader("X-Token");
        if(!Objects.isNull(token)){
            System.out.println("X-Token:"+token);
        } else {
            System.err.println("X-Token为空!");
            return true;
        }

        // 获取s(合法sessionID)
        String s = (String) servletContext.getAttribute(token); // 通过用户名获取当前合法sessionID
        if(!Objects.isNull(s)){
            System.out.println("合法sessionID:"+s);
        } else{
            System.err.println("合法sessionID为空!");
            return true;
        }

        // 获取userBean(用户对象),设置用户名
        UserBean userBean = (UserBean) servletContext.getAttribute(s);
        if(!Objects.isNull(userBean)){
            UserNameAndIpBean.setUserName(userBean.getUsername());
            System.out.println("用户名对象:"+userBean);
        }else {
            System.err.println("用户名对象为空!");
            return true;
        }

        // 获取用户IP并设置
//      String ip = HttpServletRequestCjwUtils.getRemoteIpByServletRequest(request, false);
        String ip = HttpServletRequestCjwUtils.getIpAdrress(request);
        if (!Objects.isNull(ip)){
            UserNameAndIpBean.setIP(ip);
            System.out.println("用户IP:"+ip);
        } else {
            System.err.println("用户ip地址为空!");
        }

        System.out.println("UserNameAndIpBean:"+UserNameAndIpBean.toString2());

        return true;
    }

}
